package com.cms.controller.front;

import java.util.Date;
import java.util.HashMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.entity.MessageConfig;
import com.cms.entity.SafeKey;
import com.cms.routes.RouteMapping;

/**
 * Controller - 注册
 * 
 * 
 * 
 */
@RouteMapping(url = "/register")
public class RegisterController extends BaseController{

	/**
	 * 注册页面
	 */
	public void index(){
		String qrcode = getPara("qrcode");
		setAttr("qrcode", qrcode);
        render("/templates/"+getTheme()+"/"+getDevice()+"/register_one.html");
	}
	
	/**
	 * 注册页面
	 */
	public void next(){
		String username = getPara("username");
		String qrcode = getPara("qrcode");
		setAttr("qrcode", qrcode);
		setAttr("username", username);
        render("/templates/"+getTheme()+"/"+getDevice()+"/register_two.html");
	}
	
	public void register(){
		String code = getPara("code");
		String qrcode = getPara("qrcode");
		String username = getPara("username");
        String password = getPara("password");
    	Member pMember = new Member().dao().findByMobile(username);
    	if(pMember!=null){
    		renderJson(Feedback.error("用户已存在"));
    		return;
    	}else{
    		SafeKey safeKey = new SafeKey().dao().findByMobile(username, MessageConfig.Type.REGISTER.ordinal());
    		if(!(safeKey.getValue().equals(code))){
    			renderJson(Feedback.error("短信验证码错误"));
    			return;
    		}
    		String newcode = new Member().dao().findCode();
    		Member member = new Member();
    		if(StringUtils.isNotBlank(qrcode)){
    			Member parentMember = new Member().dao().findByCode(qrcode);
    			member.setParentId(parentMember.getId());
    		}
    		member.setCode(newcode);
    		member.setMobile(username);
    		member.setPassword(DigestUtils.md5Hex(password));
    		member.setCreateDate(new Date());
    		member.setModifyDate(new Date());
    		member.setValue();
    		member.save();
    		renderJson(Feedback.success(new HashMap<>()));
    	}
	}
}
